package com.rabbitmq.provider.controller;

import com.rabbitmq.provider.entity.UserEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * @author wangdong
 * @data 2020/03/27 0027 16:09
 * @DAY 星期五
 * @描述 es测试接口
 */
@Api(value = "es接口", tags = {"es接口"})
@Scope("prototype")
@RestController
public class EsController {

    @Autowired
    private RestHighLevelClient client;

    @ApiOperation(value = "Index API允许用户将一个类型化的JSON文档索引(插入)到一个特定的索引中，并使其可搜索", notes = "Index API允许用户将一个类型化的JSON文档索引(插入)到一个特定的索引中，并使其可搜索接口")
    @ApiImplicitParams({
    })
    @RequestMapping(value = "/addUser", method = RequestMethod.GET)
    public String addUser(UserEntity vo) {
        try {
            XContentBuilder content = XContentFactory.jsonBuilder().startObject()
                    .field("age", vo.getAge())
                    .field("guid", vo.getGuid())
                    .field("name", vo.getName())
                    .field("id", vo.getId())
                    .timeField("create_time", vo.getTime())
                    .endObject();
            IndexRequest request = new IndexRequest("user").source(content);
            IndexResponse response = client.index(request, RequestOptions.DEFAULT);
            return response.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @ApiOperation(value = "Get API允许根据 id 从索引中获取一个类型化的JSON文档", notes = "Get API允许根据 id 从索引中获取一个类型化的JSON文档")
    @ApiImplicitParams({
    })
    @RequestMapping(value = "/findUserById", method = RequestMethod.GET)
    public String findUserById(String id) {
        GetRequest request = new GetRequest("user", id);
        try {
            GetResponse response = client.get(request, RequestOptions.DEFAULT);
            // 通过 response.getSource()方法我们可以拿到该文档的字段信息
            Map<String, Object> resultMap = response.getSource();
            return resultMap.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @ApiOperation(value = "update API允许通过使用脚本或传递部分文档来更新现有文档", notes = "update API允许通过使用脚本或传递部分文档来更新现有文档")
    @ApiImplicitParams({
    })
    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public String update(UserEntity vo) {
        try {
            UpdateRequest request = new UpdateRequest("user", vo.getId());
            XContentBuilder content = XContentFactory.jsonBuilder().startObject()
                    .field("age", vo.getAge())
                    .field("guid", vo.getGuid())
                    .field("name", vo.getName())
                    .timeField("create_time", vo.getTime())
                    .endObject();
            request.doc(content);
            UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
            return response.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @ApiOperation(value = "Delete API就是根据ID删除相关的文档", notes = "Delete API就是根据ID删除相关的文档")
    @ApiImplicitParams({
    })
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public String delete(String id) {
        try {
            DeleteRequest request = new DeleteRequest("user").id(id);
            DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
            return response.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @ApiOperation(value = "Search API用于与搜索文档、聚合、建议(suggestions)相关的任何操作", notes = "Search API用于与搜索文档、聚合、建议(suggestions)相关的任何操作")
    @ApiImplicitParams({
    })
    @RequestMapping(value = "/userQuery", method = RequestMethod.GET)
    public String userQuery(UserEntity vo) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (!StringUtils.isEmpty(vo.getName())) {
            boolQuery.must(QueryBuilders.matchQuery("name", vo.getName()));
        }
        if (!StringUtils.isEmpty(vo.getAge())) {
            boolQuery.must(QueryBuilders.matchQuery("age", vo.getAge()));
        }
        /*if (vo.getGtWordCount() != null && vo.getLtWordCount() != null) {
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("word_count")
                    .from(vo.getGtWordCount()).to(vo.getLtWordCount());
            boolQuery.filter(rangeQuery);
        }*/
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().query(boolQuery);
        SearchRequest searchRequest = new SearchRequest().source(searchSourceBuilder);
        try {
            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
            return response.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

}
